<template>
  <div class="menu-wrapper">
    <office-dialog ref="officeDialog" @confirm="dialogConfirm" />
    <el-form ref="sysEmployeeform" :model="sysEmployeeform" :rules="rules" label-width="80px">
      <div style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px">
        <span style="font-size: 18px;color:#409EFF;margin: 10px 0;" class="el-headerTitle">新增员工信息</span>
      </div>
        <el-form-item label="注册账号" prop="username">
            <el-input v-model="sysEmployeeform.username" style="width: 400px" />
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
            <el-input show-password v-model="sysEmployeeform.password"  style="width: 400px"/>
        </el-form-item>
        <el-form-item label="员工姓名" prop="name">
          <el-col >
            <el-input v-model="sysEmployeeform.name" style="width: 400px"></el-input>
          </el-col>
        </el-form-item>
          <el-form-item label="所属门店" prop="shopId" >
            <el-select value-key="id" v-model="sysEmployeeform.shopName" style="width: 400px" placeholder="请选择" @change="shopselect"  :filter-method="shoplistshow"  filterable >
              <el-option
                v-for="item in shoplist"
                :key="item.id"
                :label="item.name"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        <el-form-item label="联系方式" prop="phone" >
          <el-col >
            <el-input v-model="sysEmployeeform.phone" style="width: 400px"></el-input>
          </el-col>
        </el-form-item>
      <el-form-item label="员工号" prop="empNo">
        <el-input v-model="sysEmployeeform.empNo" style="width: 400px"></el-input>
      </el-form-item>

      <el-form-item label="所在岗位" >
          <el-select v-model="syspost_list" style="width: 400px" multiple placeholder="请选择岗位">
            <el-option
              v-for="item in postOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>


          <el-form-item label="绑定会员" >
           <queryMember @queryMemberClick="queryMemberClick" style="width:400px"></queryMember>
          </el-form-item>


        <el-form-item label="备注">
          <el-input type="textarea" v-model="sysEmployeeform.remark" style="width: 400px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="saveSysEmployee('sysEmployeeform')">&nbsp&nbsp立即创建&nbsp&nbsp</el-button>
        </el-form-item>

    </el-form>
  </div>
</template>
<style scoped>
  .menu-wrapper {
    margin: 15px;
  }
  .el-headerTitle{
    font-size: 20px;
    color: #409EFF;
  }
</style>
<script>
  import queryMember from '@/components/Query/queryMember'
  import {save,del,find} from '@/api/sysEmployee'
  import {list as getPostList} from '@/api/sysPost'
  import {list as members,bindEmployee} from '@/api/member'
   import {lbsList as shopList} from '@/api/shop'
  import { EventBus } from '@/api/eventBus'
  import { checkUserExists } from '@/api/sysUser'
  import utils from '../../utils/utils.js'
  import md5 from 'js-md5';
  import OfficeDialog from '@/components/OfficeDialog'
  export default {
    name:'sysEmployee-add',
    data() {
      const checkUser = (rule, value, callback) => { //检查账号是否存在
        if (utils.isNull(value)) {
          callback(new Error('请输入注册账号'))
        } else {
          const params = new URLSearchParams();
          params.append('username',value)
          checkUserExists(params).then(response => {
            console.log(response)
            if ( response.data !== 0) {
              callback(new Error('该账号已存在，不能重复'))
            } else {
              callback()
            }
          })
        }
      }
      const checkPassword = (rule, value, callback) => {
        if (value.length < 6) {
          callback(new Error('密码长度不能小于6位'))
        } else {
          callback()
        }
      }
      return {
        memberId:'',
        memberList:[],
        sysEmployeeform: {
          empNo: '',
          name: '',
          officeId: '',
          remark: '',
          status: 0,
          username:'',
          password:'',
          phone:'',
          shopId:'',
          shopName:''
        },
        rules: {
          name: [
            {required: true, message: '请输入员工名称', trigger: 'blur'},
            {min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur'}
          ],
          phone: [
            {required: true, message: '请输入手机号', trigger: 'blur'}
          ],
//          officeId: [
//            {required: true, message: '所属部门不能为空', trigger: 'blur'}
//          ],
          username: [
            { required: true, validator: checkUser, trigger: 'blur' }
          ],
          password: [
            { required: true,  validator: checkPassword, trigger: 'blur' }
          ],
//          empNo: [
//            { required: true, message: '请输入员工号', trigger: 'blur' }
//          ],
          shopId: [
            { required: true, message: '请选择所属门店', trigger: 'blur' }
          ],
        },
        loading: false,
        options: [],
        syspost_list: [],
        topName:'',
        shoplist:[],
      }
    },
    filters: {},
    components: {OfficeDialog,queryMember},
    created() {
      this.openPostList()
      this.loadMember('')
      this.shoplistshow("")
    },
    methods: {
      shopselect(val){
        this.sysEmployeeform.shopId=val.id
        this.sysEmployeeform.shopName=val.name
      },
      shoplistshow(query){
        let params = new URLSearchParams()
        params.append('keyword', query)
        shopList(params).then(res=>{
          this.shoplist=res.data
        })
      },
      queryMemberClick(data){

          this.memberId=data.memberId
      },
      loadMember(query){
        var params=new URLSearchParams()
        params.append('keyword',query)
        members(params).then(res=>{
            this.memberList=res.data.data
        })
      },
      dialogShow() {
        console.log('点击了')
        this.$refs.officeDialog.show()
      },
      dialogConfirm(val) {
        console.log(val)
        this.topName = val.name
        this.sysEmployeeform.officeId = val.id
      },
      openPostList: function () {
        let _this = this;
        let params = new URLSearchParams();
        getPostList(params).then(response => {
          console.log(response)
          _this.postOptions = response.data.data
        }).catch(error => {
          console.log('error!!')
        });
      },
      saveSysEmployee(sysEmployeeform) {
        var _this = this
        this.$refs[sysEmployeeform].validate((valid) => {
          if (valid) { // 校验表单
            _this.loading = true
            var  formData = {
              name: _this.sysEmployeeform.name,
              empNo: _this.sysEmployeeform.empNo,
              officeId: _this.sysEmployeeform.officeId,
              memberId:_this.memberId,
              userId: _this.sysEmployeeform.userId,
              remark: _this.sysEmployeeform.remark,
              status:0,
              phone: _this.sysEmployeeform.phone,
              shopId: _this.sysEmployeeform.shopId,
              shopName: _this.sysEmployeeform.shopName
            }

            const params = new URLSearchParams();
            _this.syspost_list.forEach(function (item) {
              params.append('postIds', item);
            })
            params.append('username', _this.sysEmployeeform.username)
            params.append('password', md5(_this.sysEmployeeform.password))
            console.log(formData)
            save(formData,params).then(response => {

              _this.loading = false
              _this.$message({
                message: response.content,
                offset: 120,
                center: true
              });
              EventBus.$emit('sysEmployee-add', response.data)
              _this.$store.dispatch('tagsView/delView', _this.$route).then(({ visitedViews }) => {
                _this.$router.push({
                  path: '/sysEmployee/list'
                })
              })// 关闭当前tab回到列表
            }).catch(error => {
              _this.loading = false
              console.log('error!!')
            });
          } else {
            console.log('error submit!!')
            return false
          }
        });
      }
    },
  }
</script>
